//
//  ToolDelay.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation

public typealias DelayTask = (_ cancel: Bool) ->Void
extension Tools {
    
    /// 延迟执行
    /// - Parameters:
    ///   - time: 延迟时间
    ///   - task: 任务
    /// - Returns: Task
    static public func delay(_ time: Double, task: @escaping ()->()) -> DelayTask? {
        func dispatch_later(block: @escaping ()->()) {
            let t = DispatchTime.now() + time
            DispatchQueue.main.asyncAfter(deadline: t, execute: block)
        }
        var closure: (()->Void)? = task;
        var result: DelayTask?
        let delayedClosure: DelayTask = { cancel in
            if let intermalClosure = closure {
                if (cancel == false) {
                    DispatchQueue.main.async(execute: intermalClosure)
                }
            }
            closure = nil
            result = nil
        }
        result = delayedClosure
        dispatch_later {
            if let delayedClosure = result {
                delayedClosure(false)
            }
        }
        return result
    }
    
    // 取消延迟任务
    static public func cancel(_ task: DelayTask?) {
        task?(true)
    }
}
